// index.js
// 获取应用实例
const app = getApp()
import {
  postRequest,
  getRequest
} from '../../api/request'
import {
  makePhoneCall,
  nav,
  noticeNav,
  editTabBar,
  getUrlParam,
  openLocation,
} from '../../utils/util';
import {
  linkPage,
  needParam,
  linkFunction,
  linkPageUrl,
} from '../../map.js';

Page({
  data: {
    themeColor: app.globalData.themeColor,
    subColor: app.globalData.subColor,
    btnColor: app.globalData.btnColor,
    CustomBar: app.globalData.CustomBar,
    Custom: app.globalData.Custom,
    myIndexHeadImg1: app.globalData.myIndexHeadImg1,
    myIndexHeadImg2: app.globalData.myIndexHeadImg2,
    pageInfo: [],
    showChooseScan: false, //扫描点餐弹窗
    pageTitle: "",
    backgroundObj: {
      type: 1
    },
    isDisabled: {
      componentId: false
    },
    dateRegion: {},
    pickerObjIndex: {},
    cityLocateName: '',
    isHeadShop: true,
    consultationList: [],
    color_type: {},
    users: {},
    nickName: "微信用户",
    orderNumber: {
      afterSale: 0,
      couponTotal: 0,
      waitDeliver: 0,
      waitPay: 0,
      waitReceive: 0,
    },
    globalData: {},
    isTop: 1, //是否置顶
    showNotice: false, //弹窗广告是否打开
    eventType: '', //弹窗事件类型
    eventParam: '', //弹窗事件参数
    technicalSupportIcon: '', //技术支持
  },
  dataStore: {
    pageId: 0,
    tplId: 0,
    pageTitle: '',
    shareTitle: '',
    shareImg: '',
    formData: {
      componentId: 0,
      value: '',
      localLnglat: '',
    },
    index: '',
    sbeid: ''
  },

  onShareTimeline: function (res) {
    return {
      title: '快来' + app.shopInfo.shopName + '店铺下单吧！',
      query: `pageId=${this.dataStore.pageId}&tplId=${this.dataStore.tplId}&beid=${app.beid}`, //页面携带参数
    }
  },

  onLoad(options) {
    console.log(options);
    this.dataStore.pageId = app.tabBarParam["index1"].id;
    this.dataStore.tplId = app.tabBarParam["index1"].tplId;
    if (options.pageId) {
      this.dataStore.pageId = options.pageId;
    }
    if (options.tplId) {
      this.dataStore.tplId = options.tplId;
    }
    if (options.beid) {
      app.beid = options.beid;
      this.getInitData(this)
    }
    //如果没有token,则需要重新登录获取个人信息等，避免缺少id导致数据无法获取
    if (app.token == "" || app.token == undefined) {
      app.initLogin().then(res => {
        this.getInitData(this)
      }).catch(err => {})
    } else {
      this.getInitData(this);
    }

  },
  //获取店铺风格
  getShopInfo() {
    let that = this;
    getRequest("/api/shop/getShopInfo", {
      beid: app.beid
    }).then(res => {
      console.log(res, 'res')
      app.globalConfig = res.data.data;
      app.globalData.service_phone = res.data.data.service_phone
      app.globalData.shop_name = res.data.data.mini_name
      app.globalData.address = res.data.data.address
      app.globalData.open_time_periods = res.data.data.open_time_periods
      app.globalData.lnglat = res.data.data.lnglat
      //主题色
      if (res.data.data.colorType != '' && res.data.data.colorType != null) {
        app.globalData.themeColor = res.data.data.colorType.themeColor;
        app.globalData.subColor = res.data.data.colorType.subColor;
        app.globalData.btnColor = res.data.data.colorType.btnColor;
        that.setData({
          themeColor: res.data.data.colorType.themeColor,
          subColor: res.data.data.colorType.subColor,
          btnColor: res.data.data.colorType.btnColor,
        })
      }
      that.setData({
        globalData: res.data.data,
        isTop: res.data.data.isTop,
      })
      wx.setStorageSync('shopInfo', res.data.data);
      wx.setStorageSync('paymentPriority', res.data.data.paymentPriority)
      // todo 
    }).catch((err) => {
      console.log(err)
    });
  },
  //广告弹窗----------------------------------------------------------开始
  //获取弹窗
  getFirstOnlineNotice() {
    let self = this;
    getRequest('/api/notice/getFirstOnlineNotice', {
      effectPage: 1
    }).then((res) => {
      console.log(res);
      if (res.statusCode == 200) {
        if (res.data.data != null) {
          let data = res.data.data;
          if (data.isTurn == 1 && data.turnEvent != '') {
            self.data.eventType = JSON.parse(data.turnEvent).eventType
            self.data.eventParam = JSON.parse(data.turnEvent).eventParam
          }
          if (!data.id) {
            return
          }
          //判断时间，永久还是限时
          let isInvalid = data.isForever == 0 && (Date.parse(new Date()) < Date.parse(data.startTime) || Date.parse(new Date()) > Date.parse(data.endTime));
          if (isInvalid) {
            return;
          }
          //打开即显示1，只显示一次2，每天第一次打开显示3
          //是否显示过
          let noticeInfo = wx.getStorageSync('noticeKey');
          if (data.showType == 1 && ((!noticeInfo || noticeInfo.id != data.id))) {
            self.setShow(self, data.imageUrl);
            // setStorage(data);
            return;
          }
          if (data.showType == 1 && ((!noticeInfo || noticeInfo.id == data.id))) {
            self.setShow(self, data.imageUrl);
            setStorage(data);
            return;
          }
          try {
            if (!noticeInfo || noticeInfo.id != data.id) {
              self.setShow(self, data.imageUrl);
              self.setStorage(data);
            } else {
              if (data.showType == 2 && noticeInfo.openTime) {
                return;
              } else if (getYMD(new Date(noticeInfo.openTime)) != getYMD(new Date()) && data.showType == 3) {
                self.setShow(self, data.imageUrl);
                self.setStorage(data);
              }
            }
          } catch (e) {}
        }
      }
    })
  },
  //显示弹窗
  setShow(self, url) {
    self.setData({
      showNotice: true,
      noticeImgUrl: url
    })
  },
  //设置弹窗缓存，用以判断是否打开过等
  setStorage(data) {
    wx.setStorageSync("noticeKey", {
      'id': data.id,
      'isForever': data.isForever,
      'startTime': data.startTime,
      'endTime': data.endTime,
      "showType": data.showType,
      'noticeImgUrl': data.imageUrl,
      'openTime': Date.parse(new Date()),
    })
  },
  //弹窗跳转
  navLink() {
    this.hideNotice();
    if (this.data.eventType != '') {
      noticeNav(this.data.eventType, this.data.eventParam)
    }
  },
  //关闭弹窗
  hideNotice() {
    this.setData({
      showNotice: false,
    });
  },
  //广告弹窗----------------------------------------------------------结束
  //空的方法，用来阻止冒泡的
  handmiddle() {

  },
  //打开导航
  opLocations() {
    console.log(this.data.globalData, 'this.data.globalData')
    let arr = this.data.globalData.lnglat.split(',')
    const latitude = Number(arr[1])
    const longitude = Number(arr[0])
    wx.openLocation({
      latitude,
      longitude,
      name: this.data.globalData.shopName,
      address: this.data.globalData.address,
      scale: 18
    })
  },
  //跳转技术支持页面
  goApp() {
    wx.navigateToMiniProgram({
      appId: 'wx4ef45ca79b4ddfac',
      path: 'pages/index1/index1',
      extraData: {
        foo: 'bar'
      },
      envVersion: 'release',
      success(res) {
        // 打开成功
      }
    })
  },
  //跳转其他小程序
  navigateToMiniProgram(param) {
    wx.navigateToMiniProgram({
      appId: param.id,
      path: param.appPath,
      fail: err => {
        showModal({
          title: "打开错误"
        })
      }
    })
  },
  //获取页面初始化数据
  getInitData(self) {
    let _this = self;
    //店铺信息
    _this.getShopInfo()

    let parame = {
      tplId: self.dataStore.tplId,
      pageId: self.dataStore.pageId
    }

    _this.getFirstOnlineNotice();

    wx.stopPullDownRefresh()

    getRequest("/api/msg/getTplPageSimple", parame).then((res) => {
      console.log(res.data.data);
      //技术支持图片
      var imgIcon = wx.getStorageSync('shopInfo');
      if (imgIcon != undefined && imgIcon != '') {
        _this.setData({
          technicalSupportIcon: imgIcon.technicalSupportIcon,
        })
      }
      let pageInfo = res.data.data.tpl,
        backgroundObj = res.data.data.pageConfig.BackgroundObj,
        pickerObjIndex = {}
      self.setData({
        pageTitle: res.data.data.title,
      })
      self.dataStore.pageTitle = res.data.data.title;
      self.dataStore.sbeid = res.data.data.beid
      // 分享封面的标题和图片
      self.dataStore.shareImg = res.data.data.img_url;
      self.dataStore.shareTitle = res.data.data.share;
      wx.setNavigationBarTitle({
        title: self.dataStore.pageTitle
      })
      let flag = 0
      //循环页面
      console.log(pageInfo);
      for (let i = 0; i < pageInfo.length; i++) {
        //用户信息条
        if (pageInfo[i].type == 'menber') {
          if (app.myInfo.memberId) {
            getRequest("/api/vip/getUserBaseInfo", {
              memberId: app.myInfo.memberId,
            }).then((ures) => {
              if (ures.data.data.avatar == '') {
                if (ures.data.data.gender == 2) {
                  ures.data.data.avatar = self.data.myIndexHeadImg2;
                } else {
                  ures.data.data.avatar = self.data.myIndexHeadImg1;
                }
              }
              _this.setData({
                users: ures.data.data,
              })
            }).catch((err) => {});
          }
        }
        //文字
        if (pageInfo[i].type == 'text') {
          pageInfo[i].type = 'onlyText';
          pageInfo[i].data.text = pageInfo[i].data.text.replace(/ /g, '　');
        }
        //搜索
        if (pageInfo[i].type == 'searchBox') {
          pageInfo[i].eventType = 'searchPage';
          pageInfo[i].eventParam = {
            searchType: pageInfo[i].searchType
          };
          if (pageInfo[i].cityLocate) {
            flag += 1;
          }
        }
        //表单
        if (pageInfo[i].type == 'form') {
          for (let j = 0; j < pageInfo[i].data.length; j++) {
            if (pageInfo[i].data[j].controlStyle == 'dropDown' && pageInfo[i].data[j].formType == 'radio') {
              pageInfo[i].data[j].formType = 'singlePicker'
              let key = '_' + pageInfo[i].data[j].id;
              pickerObjIndex[key] = {
                formIndex: j,
                pickeIndex: 0
              };
            }
          }
        }
        //动态内容
        if (pageInfo[i].type == 'contentsDynamicComponent') {
          var newsIds = pageInfo[i].data.map(i => i.newsid).join(',');
          delete pageInfo[i].data;
          pageInfo[i].newsIds = newsIds;
        }
        //动态商品
        if (pageInfo[i].type == 'goodsDynamicComponent') {
          var gids = pageInfo[i].data.map(i => i.gid).join(',');
          delete pageInfo[i].data;
          pageInfo[i].gids = gids;
        }
        //动态商人
        if (pageInfo[i].type == 'merchantDynamicComponent') {
          var mids = pageInfo[i].data.map(i => i.mid).join(',');
          delete pageInfo[i].data;
          pageInfo[i].mids = mids;
        }
        //vue的地图
        if (pageInfo[i].type == 'vuemap') {

          if (!pageInfo[i].lnglat) {
            // 人民广场吃炸鸡
            pageInfo[i].lnglat = "121.481587,31.23494";
          }

          var loc = pageInfo[i].lnglat.split(',');
          pageInfo[i]['markers'] = [{
            iconPath: "/imgs/mark_bs.png",
            id: 1,
            latitude: loc[1],
            longitude: loc[0],
            width: 19,
            height: 33,
            callout: {
              content: pageInfo[i].address,
              color: '#000',
              fontSize: 12,
              borderRadius: 3,
              padding: 5,
              display: 'ALWAYS',
              bgColor: '#FFEC8B',
            }
          }];
          pageInfo[i]['lat'] = loc[1];
          pageInfo[i]['lng'] = loc[0];
        }
      }

      self.setData({
        pageInfo,
        backgroundObj,
        pickerObjIndex,
      })

      console.log('pageData', this.data)

    }).catch((err) => {});
  },
  navUrl(e) {
    console.log(e)
    let url = e.currentTarget.dataset.url
    wx.navigateTo({
      url: url
    })
  },
  //事件跳转
  async eventTap(e) {
    let eventType = e.currentTarget.dataset.eventType,
      eventParam = e.currentTarget.dataset.eventParam;

    console.log(e);
    console.log(linkPage.indexOf(eventType));
    console.log(linkFunction[eventType]);
    //如果是需要参数的页面则要传参数
    if (needParam.indexOf(eventType) >= 0 && eventParam.length == 0) {
      showModal({
        title: '提示',
        content: "您未传入有效参数"
      })
      return;
    }
    if (linkPage.indexOf(eventType) >= 0) {
      //在链接页面
      //外部链接
      if (eventType == 'webView') {
        let url = eventParam.url
        var urlArr = url.split('?')
        if (urlArr[1]) {
          let newArr = [];
          let parameter = urlArr[1].split('&')
          parameter.forEach(item => {
            newArr.push(item.split('=')[0], item.split('=')[1])
          })
          eventParam.url = urlArr[0]
          eventParam.parameter = JSON.stringify(newArr)
        }
      }
      //商品详情页
      if(eventType == 'foodsDetail'){
        wx.navigateTo({
          url: '/pages/goodsDetail/goodsDetail?id=' + eventParam.id + '&saleType=2&orderType=2&deskCode=&deskId=',
        })
        return;
      }

      // end 服务列表
      nav({
        url: eventType == 'DIYPage' ? '/pages/index/index' : `${linkPageUrl[eventType]}`,
        data: eventParam
      });
    } else if (linkFunction[eventType]) {
      console.log(linkFunction);
      console.log(eventType);
      this[linkFunction[eventType]](eventParam);
    } else if (eventType == 'merchantDetail') {
      // return

      // 
      await this.getShopListNew(eventParam)
      await getGlobalConfig(this, true) //跳转商户，更新config
      if (!eventParam.navType || (eventParam.navType && eventParam.navType == 1)) {

        wx.reLaunch({
          url: '/pages/index1/index1'
        })
      } else if (eventParam.navType && eventParam.navType == 2) {
        if (eventParam.version && eventParam.version == 3) {
          // 跳转商户 只接受relaunch
          wx.reLaunch({
            url: `/pages/goodsdetail/goodsdetail?goodsId=${eventParam.goodsId}`,
          })
        } else {
          wx.reLaunch({
            url: `/pages/foodsDetail/foodsDetail?id=${eventParam.goodsId}`,
          })
        }
      }


    }
  },
  //图片点击
  previewImg(e) {
    let id = e.currentTarget.dataset.id,
      pageInfo = this.data.pageInfo,
      fromType = e.currentTarget.dataset.fromType || '',
      imgUrl = e.currentTarget.dataset.url,
      imgArr = [];
      console.log('dddd',e.currentTarget.dataset)
    for (let i = 0; i < pageInfo.length; i++) {
      if (pageInfo[i].id == id) {
        if (fromType == 'picture') {
          imgArr[0] = pageInfo[i].data;

        } else {
          imgArr = pageInfo[i].data;
        }

        break;
      }
    }
    previewImageList(imgArr, 'path', imgUrl);

  },
  //跳转到个人页
  tapName() {
    wx.navigateTo({
      url: '../myInfo/myInfo',
    })
  },
  //打开扫描点餐
  showChooseScan() {
    this.setData({
      showChooseScan: true
    })
  },
  //关闭扫描点餐
  closechooseScanBox() {
    this.setData({
      showChooseScan: false
    })
  },
  //扫描餐桌二维码
  scanQrcodeEnter() {
    console.log("wx.scanCodejinlaile");
    // wx.clearStorageSync("deskName")
    // wx.clearStorageSync('deskCode')
    // wx.clearStorageSync('deskId')
    // wx.clearStorageSync('orderId')
    let self = this;
    let deskCode = '';
    let deskId = '';
    wx.scanCode({
      success: (res) => {
        console.log("wx.scanCode",res);
        try {
          self.setData({
            showChooseScan: false
          });
          deskCode = getUrlParam('deskCode', res.path);
          deskId = getUrlParam('deskId', res.path);
          app.globalData.deskCode = deskCode;
          app.globalData.deskId = deskId;
          app.globalData.deskName = deskCode;
          wx.setStorageSync('deskName',deskCode)
          wx.setStorageSync('deskCode',deskCode)
          wx.setStorageSync('deskId',deskId)
          // wx.setStorageSync('addBtnFoods',true)
          nav({
            url: '/pages/queueMenu/queueMenu?deskCode=' + deskCode + '&deskId=' + deskId
          })
        } catch (e) {
          wx.showToast({
            title: '二维码不正确',
            icon: 'none'
          })
        };
      }
    })
  },
  //拨打电话
  callPhone(param) {
    makePhoneCall(param.phone);
  },
  //拨打电话
  makePhoneCall(e) {
    makePhoneCall(e.currentTarget.dataset.phone);
  },
  //打开导航
  openLocation(param) {
    let latitude = Number(param.lnglat.split(',')[1]),
      longitude = Number(param.lnglat.split(',')[0]),
      address = param.address || '';
    openLocation(latitude, longitude, address);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    editTabBar(this, 'index')
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 停止下拉刷新效果
    this.getInitData(this);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})